package cn.com.dhc.danlu.util;

import android.content.Context;
import android.os.Environment;

import java.io.File;


/**
 * User: Geek_Soledad(wuhaiyang@andthink.cn)
 * Date: 2016-03-19
 * Time: 15:47
 * Description:
 */
public class FileManager {
    private static final String ROOT = "danluz";

    private static final String IMAGE = "image"; //缓存应用程序的图片的文件夹
    private static final String CACHE = "cache";//缓存应用程序数据的文件夹
    private static final String APK = "apk";

    private static File getDir (Context context, String str) {
        StringBuilder sb = new StringBuilder ();
        if (CommonUtils.existSDCard ()) {
            sb.append (Environment.getExternalStorageDirectory ().getAbsolutePath ()); // mnt/sdcard
            sb.append (File.separator);
            sb.append (ROOT); // mnt/sdcard/applicationame
            sb.append (File.separator);//
            sb.append (str);// mnt/sdcard/applocationname/str
        } else {
            File cacheFile = context.getCacheDir ();
            sb.append (cacheFile.getAbsolutePath ());//// data/data/packagename/cache
            sb.append (File.separator);
            sb.append (str);
        }
        File file = new File (sb.toString ());
        if (!file.exists () || !file.isDirectory ()) {
            file.mkdirs ();
        }
        return file;
    }

    public static File getCacheDir (Context context) {
        return getDir (context, CACHE);
    }

    public static File getImageDir (Context context) {
        return getDir (context, IMAGE);
    }

    public static File getApkDir (Context context) {
        return getDir (context, APK);
    }

    //删除指定文件夹下所有文件
    //param path 文件夹完整绝对路径
    public static boolean delAllFile (String path) {
        boolean flag = false;
        File file = new File (path);
        if (!file.exists ()) {
            return false;
        }
        if (!file.isDirectory ()) {
            return false;
        }
        String[] tempList = file.list ();
        File temp;
        for (String aTempList : tempList) {
            if (path.endsWith (File.separator)) {
                temp = new File (path + aTempList);
            } else {
                temp = new File (path + File.separator + aTempList);
            }
            if (temp.isFile ()) {
                temp.delete ();
            }
            if (temp.isDirectory ()) {
                delAllFile (path + "/" + aTempList);//先删除文件夹里面的文件
                delFolder (path + "/" + aTempList);//再删除空文件夹
                flag = true;
            }
        }
        return flag;
    }

    //删除文件夹
    //param folderPath 文件夹完整绝对路径
    private static void delFolder (String folderPath) {
        try {
            delAllFile (folderPath); //删除完里面所有内容
            File myFilePath = new File (folderPath);
            myFilePath.delete (); //删除空文件夹
        } catch (Exception e) {
            e.printStackTrace ();
        }
    }
}  